package com.shuqi.common;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Log4an;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.RefreshBalanceModel;
import com.shuqi.model.bean.AccountBalanceInfo;
import com.shuqi.model.manager.MyAccountManager;

/**获取余额*/
public class RefreshBalanceTask {
    private static RefreshBalanceTask refreshBalanceTask;
    private static RefreshBalanceModel model;
    private String logTag = "RefreshBalanceTask";
    private RefreshBalanceTask(){}
    public static RefreshBalanceTask getInstance(){
        if(refreshBalanceTask == null){
            refreshBalanceTask = new RefreshBalanceTask();
        }
        return refreshBalanceTask;
    }
    
    /***
     * 联网刷新用户余额(自动保存本地数据库)
     * <B>在子线程回调</B>
     * @param listener
     */
    public synchronized void refreshBalanceOnline(final RefreshBlanceListener listener){
        if(model==null){
            model = new RefreshBalanceModel(ShuqiApplication.getContext());
        }
        if(model.isLoading()){
            Log4an.e(logTag, "refreshBalance() isLoading return");
            return;
        }
        Log4an.i(logTag, "refreshBalanceOnline() start...");
        model.addEventListener(new IEventListener() {
            @Override
            public void onEvent(int event, Object data) {
                UserInfo userInfo = MyAccountManager.getInstance(ShuqiApplication.getContext());
                if(event == EventTypeConstants.EVENT_SUCCESS){
                    AccountBalanceInfo balanceInfo = (AccountBalanceInfo) data;
                    if (balanceInfo!=null && "1".equals(balanceInfo.getMsgCode())) {
                        userInfo.setBalance(balanceInfo.getBalance());
                        MyAccountManager.onUpdateUserInfo(userInfo);
                        if(listener!=null){
                            listener.onFinish(true, balanceInfo.getBalance());
                        }
                        Log4an.i(logTag, "refreshBalanceOnline() onFinish: ok , balance="+balanceInfo.getBalance());
                        return;
                    }
                }
                if(listener!=null){
                    listener.onFinish(false, userInfo.getBalance());
                }
                Log4an.i(logTag, "refreshBalanceOnline() onFinish: error , balance="+userInfo.getBalance());
            }
        });
        model.loadData("");
    }
    
    public interface RefreshBlanceListener{
        public void onFinish(boolean isSuccess,String balance);
    }
        
}
